﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;

namespace Common
{
   public class QrCodeMethod
    {

        //生成二维码方法一
        public void CreateCode_Simple(string nr,ref string ImageUrl)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 4;
            qrCodeEncoder.QRCodeVersion = 8;
            // qrCodeEncoder.QRCodeBackgroundColor = Color.Blue;//背景色
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
           // qrCodeEncoder.QRCodeForegroundColor = Color.Blue;//前景色
            System.Drawing.Image image = qrCodeEncoder.Encode(nr, Encoding.UTF8);//此步骤 二维码已经生成
            string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
        
            string filepath = System.Configuration.ConfigurationManager.AppSettings["imgUrl"] + filename;
            ImageUrl = filepath;
            System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);

            fs.Close();
            image.Dispose();
            //二维码解码
            var codeDecoder = CodeDecoder(filepath);
        }

        /// <summary>
        /// 二维码解码
        /// </summary>
        /// <param name="filePath">图片路径</param>
        /// <returns></returns>
        public string CodeDecoder(string filePath)
        {
            if (!System.IO.File.Exists(filePath))
                return null;
            Bitmap myBitmap = new Bitmap(Image.FromFile(filePath));
            QRCodeDecoder decoder = new QRCodeDecoder();
            string decodedString = decoder.decode(new QRCodeBitmapImage(myBitmap));
            return decodedString;
        }

    }
}
